package vh.sphynx.jobengine;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import vh.sphynx.runtime.ExecutionContext;
import vh.sphynx.runtime.SphynxInterpreter;
import vh.sphynx.runtime.VariableStorage;
import vh.sphynx.runtime.interpreter.XFunctionDeclartationInterpreter;
import vh.sphynx.sphynx.XFeatureCall;
import vh.sphynx.sphynx.XFunctionDeclaration;
import vh.sphynx.util.SphynxRuntimeUtil;

public class SphynxScriptJob extends AbstractJob {

	private static final long serialVersionUID = -1018996893510636175L;

	private XFunctionDeclaration function;
	private ExecutionContext context;
	private Map<String, Object> args;
	private SphynxInterpreter interpreter;
	
	public static SphynxScriptJob createJob(SphynxInterpreter interpreter, 
			ExecutionContext context, XFunctionDeclaration func) {
		Map<String, Object> args = new HashMap<String, Object>();
		Collection<String> names = context.getVariableNames(VariableStorage.ARGUMENT);
		
		for (String varName: names) 
			if (!"__args".equals(varName) && !"func".equalsIgnoreCase(varName)) {
				Object value = context.getVariable(varName, false, false).getValue();
				args.put(varName, value);
			}
		return new SphynxScriptJob(interpreter, context, func, args);
	}
	
	public SphynxScriptJob(SphynxInterpreter interpreter, 
			ExecutionContext context, XFunctionDeclaration statement, 
			Map<String, Object> args) {
		this.context = context;
		this.function = statement; 
		this.interpreter = interpreter;
		this.args = args;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void executeJob(Object _args) throws Exception {
		XFeatureCall call = SphynxRuntimeUtil.createFeatureCall(function, args);
		interpreter.evaluate(call, context);
	}

}
